﻿using BootstrapBlazor.Components;
using Common.Api.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Components
{
    public class InputUploadPicture : AvatarUpload<int>
    {
        public InputUploadPicture()
        {
            this.OnChange = OnFileChange;
            this.OnDelete = OnDeletePictrue;
            this.IsSingle = true;
        }
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                await LoadPicture();
            }
            await base.OnAfterRenderAsync(firstRender);
        }

        private string PictureLoading = "_content/CyssBlazor.Shared/img/picture_loading.gif";

        private async Task<bool> OnDeletePictrue(UploadFile file)
        {
            this.Value = 0;
            return true;
        }

        private async Task OnFileChange(UploadFile file)
        {
            file.PrevUrl = PictureLoading;
            SetDisable(true);
            var imageFile = file.File;
            var operateResult = await CommonClientFactory.Picture.AsyncUpload(imageFile.OpenReadStream(maxAllowedSize: long.MaxValue), imageFile.Name);
            if (operateResult.IsSuccess)
            {
                this.CurrentValue = operateResult.Data.PictureId;
                this.Value = operateResult.Data.PictureId;
                file.PrevUrl = operateResult.Data.ImageUrl;
            }
            IsDisabled = false;
            await InvokeAsync(StateHasChanged);
        }

        /// <summary>
        /// 初始加载图片
        /// </summary>
        private async Task LoadPicture()
        {
            if (this.Value > 0)
            {
                if (this.CurrentFile == null)
                {
                    this.CurrentFile = new UploadFile();
                }
                this.UploadFiles.Add(this.CurrentFile);
                this.CurrentFile.PrevUrl = this.PictureLoading;
                await InvokeAsync(StateHasChanged);
                var operateResult = await CommonClientFactory.Picture.GetPictureUrlById(this.Value, 100);
                if (operateResult.IsSuccess)
                {
                    this.CurrentFile.PrevUrl = operateResult.Data.ImageUrl;
                }
                else
                {
                    // this.CurrentFile.PrevUrl = this.PictureFail;
                }
                await InvokeAsync(StateHasChanged);
            }
        }

    }
}
